package cn.felord.sse.api;

import cn.felord.sse.entity.MessageBody;
import cn.felord.sse.event.NewOrderNotifyEvent;
import cn.felord.sse.event.NewOrderNotifyEventPublisher;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author Dax
 * @since 09:43  2019/8/22
 */
@RestController
public class SseApi {

    private Map<String, SseEmitter> sseEmitterMap = new HashMap<>();

    @Resource
    private NewOrderNotifyEventPublisher newOrderNotifyEventPublisherAware;

    @GetMapping(path = "/events/{id}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @CrossOrigin
    public SseEmitter handle(@PathVariable String id) {
        SseEmitter sseEmitter = new SseEmitter();

        this.sseEmitterMap.put(id, sseEmitter);
        return sseEmitter;
    }

    @CrossOrigin
    @GetMapping("/send/{id}")
    public String send(@PathVariable String id) {
        Map<String, String> map = new HashMap<>(1);
        map.put("timestamp", LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));

        MessageBody<Map<String, String>> body = new MessageBody<>();
        body.setFrom("SERVER");
        body.setTo(id);
        body.setPayload(map);

        Optional.of(sseEmitterMap.get(id)).ifPresent(sseEmitter -> {
            NewOrderNotifyEvent event = new NewOrderNotifyEvent(false, body, sseEmitter);
            newOrderNotifyEventPublisherAware.publish(event);
        });

        return "ok";
    }

    public static void main(String[] args) {
        // List<String> list = null;
        List<String> list = new ArrayList<>();
        list.add("a");
        list.add("b");
        Optional.ofNullable(list).ifPresent(e -> {
            e.forEach(o -> {
                System.out.println(o);
            });
        });
        System.out.println("ok");
    }
}
